import { useState, useEffect } from 'react'
import { Table, Button, Modal, Tag, Space, Input, Select, message, Card, Statistic } from 'antd'
import { 
  SearchOutlined, 
  EyeOutlined, 
  CheckOutlined, 
  CloseOutlined,
  FilterOutlined,
  ExportOutlined
} from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import dayjs from 'dayjs'

const { Option } = Select

interface FeedbackType {
  id: string
  title: string
  content: string
  username: string
  contact: string
  status: 'pending' | 'resolved' | 'rejected'
  createdAt: string
  resolvedAt?: string
  handler?: string
  reply?: string
}

export default function FeedbackManagement() {
  const [feedbacks, setFeedbacks] = useState<FeedbackType[]>([])
  const [loading, setLoading] = useState(false)
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [currentFeedback, setCurrentFeedback] = useState<FeedbackType | null>(null)
  const [searchParams, setSearchParams] = useState({
    keyword: '',
    status: 'all'
  })
  const [replyContent, setReplyContent] = useState('')

  // 模拟从API获取反馈数据
  useEffect(() => {
    fetchFeedbacks()
  }, [])

  const fetchFeedbacks = () => {
    setLoading(true)
    // 这里应该是API调用，我们使用模拟数据
    setTimeout(() => {
      const mockFeedbacks: FeedbackType[] = [
        {
          id: '1',
          title: '网站加载速度慢',
          content: '首页加载需要5秒以上，希望能优化',
          username: 'user123',
          contact: 'user123@example.com',
          status: 'resolved',
          createdAt: '2023-05-10T09:12:33Z',
          resolvedAt: '2023-05-11T14:30:15Z',
          handler: 'admin',
          reply: '已优化前端资源加载策略，速度提升明显'
        },
        {
          id: '2',
          title: '产品图片不清晰',
          content: '商品详情页的图片放大后模糊',
          username: 'user456',
          contact: 'user456@example.com',
          status: 'pending',
          createdAt: '2023-05-15T16:45:22Z'
        },
        {
          id: '3',
          title: '支付失败问题',
          content: '在最后支付步骤提示系统错误',
          username: 'user789',
          contact: '13800138000',
          status: 'rejected',
          createdAt: '2023-05-18T11:05:47Z',
          resolvedAt: '2023-05-18T11:30:00Z',
          handler: 'admin',
          reply: '经检查是用户网络问题导致，已建议用户更换网络环境'
        }
      ]
      setFeedbacks(mockFeedbacks)
      setLoading(false)
    }, 500)
  }

  // 过滤反馈数据
  const filteredFeedbacks = feedbacks.filter(feedback => {
    const matchesKeyword = 
      feedback.title.toLowerCase().includes(searchParams.keyword.toLowerCase()) ||
      feedback.content.toLowerCase().includes(searchParams.keyword.toLowerCase()) ||
      feedback.username.toLowerCase().includes(searchParams.keyword.toLowerCase())
    
    const matchesStatus = 
      searchParams.status === 'all' || feedback.status === searchParams.status
    
    return matchesKeyword && matchesStatus
  })

  const handleView = (feedback: FeedbackType) => {
    setCurrentFeedback(feedback)
    setReplyContent(feedback.reply || '')
    setIsModalOpen(true)
  }

  const handleStatusChange = (id: string, status: 'resolved' | 'rejected') => {
    // 这里应该是API调用
    const updatedFeedbacks = feedbacks.map(feedback => {
      if (feedback.id === id) {
        return {
          ...feedback,
          status,
          resolvedAt: new Date().toISOString(),
          handler: 'current_admin', // 实际应该获取当前管理员用户名
          reply: replyContent
        }
      }
      return feedback
    })
    setFeedbacks(updatedFeedbacks)
    setIsModalOpen(false)
    message.success(`反馈已标记为${status === 'resolved' ? '已解决' : '已拒绝'}`)
  }

  const getStatusTag = (status: string) => {
    switch (status) {
      case 'pending':
        return <Tag color="orange">待处理</Tag>
      case 'resolved':
        return <Tag color="green">已解决</Tag>
      case 'rejected':
        return <Tag color="red">已拒绝</Tag>
      default:
        return <Tag>未知</Tag>
    }
  }

  const columns: ColumnsType<FeedbackType> = [
    {
      title: '反馈标题',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      render: (text, record) => (
        <a onClick={() => handleView(record)}>{text}</a>
      )
    },
    {
      title: '反馈内容',
      dataIndex: 'content',
      key: 'content',
      ellipsis: true,
      width: 300
    },
    {
      title: '提交用户',
      dataIndex: 'username',
      key: 'username',
      width: 120
    },
    {
      title: '联系方式',
      dataIndex: 'contact',
      key: 'contact',
      width: 150
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: status => getStatusTag(status)
    },
    {
      title: '提交时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: text => dayjs(text).format('YYYY-MM-DD HH:mm')
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="text" 
            icon={<EyeOutlined />} 
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          {record.status === 'pending' && (
            <Button 
              type="text" 
              danger 
              icon={<CloseOutlined />}
              onClick={() => handleStatusChange(record.id, 'rejected')}
            >
              拒绝
            </Button>
          )}
        </Space>
      ),
    },
  ]

  // 统计反馈数据
  const stats = {
    total: feedbacks.length,
    pending: feedbacks.filter(f => f.status === 'pending').length,
    resolved: feedbacks.filter(f => f.status === 'resolved').length,
    rejected: feedbacks.filter(f => f.status === 'rejected').length
  }

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <h2>用户反馈管理</h2>
        <p>处理和分析用户提交的网站反馈信息</p>
        
        {/* 统计卡片 */}
        <div style={{ display: 'flex', gap: 16, marginBottom: 24 }}>
          <Card>
            <Statistic title="总反馈数" value={stats.total} />
          </Card>
          <Card>
            <Statistic title="待处理" value={stats.pending} />
          </Card>
          <Card>
            <Statistic title="已解决" value={stats.resolved} />
          </Card>
          <Card>
            <Statistic title="已拒绝" value={stats.rejected} />
          </Card>
        </div>

        {/* 搜索和筛选 */}
        <Space style={{ marginBottom: 16 }}>
          <Input
            placeholder="搜索反馈"
            prefix={<SearchOutlined />}
            value={searchParams.keyword}
            onChange={e => setSearchParams({...searchParams, keyword: e.target.value})}
            style={{ width: 300 }}
          />
          <Select
            placeholder="选择状态"
            style={{ width: 120 }}
            value={searchParams.status}
            onChange={value => setSearchParams({...searchParams, status: value})}
          >
            <Option value="all">全部状态</Option>
            <Option value="pending">待处理</Option>
            <Option value="resolved">已解决</Option>
            <Option value="rejected">已拒绝</Option>
          </Select>
          <Button icon={<FilterOutlined />}>高级筛选</Button>
          <Button icon={<ExportOutlined />}>导出数据</Button>
        </Space>
      </div>

      <Table
        columns={columns}
        dataSource={filteredFeedbacks}
        rowKey="id"
        loading={loading}
        bordered
        pagination={{ pageSize: 10 }}
        scroll={{ x: 1300 }}
      />

      <Modal
        title="反馈详情"
        open={isModalOpen}
        onCancel={() => setIsModalOpen(false)}
        footer={currentFeedback?.status === 'pending' ? (
          <Space>
            <Button 
              type="primary" 
              icon={<CheckOutlined />}
              onClick={() => handleStatusChange(currentFeedback.id, 'resolved')}
            >
              标记为已解决
            </Button>
            <Button 
              danger 
              icon={<CloseOutlined />}
              onClick={() => handleStatusChange(currentFeedback.id, 'rejected')}
            >
              标记为已拒绝
            </Button>
            <Button onClick={() => setIsModalOpen(false)}>取消</Button>
          </Space>
        ) : (
          <Button onClick={() => setIsModalOpen(false)}>关闭</Button>
        )}
        width={800}
      >
        {currentFeedback && (
          <div>
            <div style={{ marginBottom: 16 }}>
              <h3>{currentFeedback.title}</h3>
              <p style={{ color: '#666' }}>提交用户: {currentFeedback.username}</p>
              <p style={{ color: '#666' }}>联系方式: {currentFeedback.contact}</p>
              <p style={{ color: '#666' }}>提交时间: {dayjs(currentFeedback.createdAt).format('YYYY-MM-DD HH:mm')}</p>
              <Tag color={currentFeedback.status === 'pending' ? 'orange' : 
                          currentFeedback.status === 'resolved' ? 'green' : 'red'}>
                {currentFeedback.status === 'pending' ? '待处理' : 
                 currentFeedback.status === 'resolved' ? '已解决' : '已拒绝'}
              </Tag>
              {currentFeedback.resolvedAt && (
                <p style={{ color: '#666' }}>
                  处理时间: {dayjs(currentFeedback.resolvedAt).format('YYYY-MM-DD HH:mm')}
                </p>
              )}
              {currentFeedback.handler && (
                <p style={{ color: '#666' }}>处理人: {currentFeedback.handler}</p>
              )}
            </div>

            <div style={{ marginBottom: 24 }}>
              <h4>反馈内容</h4>
              <div style={{ 
                padding: 12, 
                background: '#f5f5f5', 
                borderRadius: 4,
                marginBottom: 16
              }}>
                {currentFeedback.content}
              </div>
            </div>

            {currentFeedback.status !== 'pending' ? (
              <div>
                <h4>处理回复</h4>
                <div style={{ 
                  padding: 12, 
                  background: '#f0f9eb', 
                  borderRadius: 4 
                }}>
                  {currentFeedback.reply}
                </div>
              </div>
            ) : (
              <div>
                <h4>回复内容</h4>
                <Input.TextArea 
                  rows={4} 
                  value={replyContent}
                  onChange={e => setReplyContent(e.target.value)}
                  placeholder="请输入处理回复内容"
                />
              </div>
            )}
          </div>
        )}
      </Modal>
    </div>
  )
}